﻿using System;
using System.Text;

public static class Base64Util
{
    public static string Encode(byte[] buf)
    {
        return Convert.ToBase64String(buf);
    }

    public static string Encode(string plainText)
    {
        if (string.IsNullOrEmpty(plainText))
            return string.Empty;

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        return Convert.ToBase64String(plainTextBytes);
    }
    public static byte[] Decode2Bytes(string base64String)
    {
        if (string.IsNullOrEmpty(base64String))
            return null;

        // 计算需要添加的填充字符个数
        //int paddingCount = base64EncodedText.Length % 4;
        //if (paddingCount > 0)
        //{
        //    paddingCount = 4 - paddingCount;
        //    base64EncodedText += new string('=', paddingCount);
        //}

        // 检查输入字符串的长度是否是 4 的倍数
        int paddingLength = base64String.Length % 4;
        if (paddingLength > 0)
        {
            base64String = base64String.PadRight(base64String.Length + (4 - paddingLength), '=');
        }

        // 检查是否存在非法字符
        base64String = base64String.Replace("_", "+").Replace("-", "/");

        return Convert.FromBase64String(base64String);
    }
    public static string Decode(string base64EncodedText)
    {
        byte[] base64Bytes = Decode2Bytes(base64EncodedText);
        return Encoding.UTF8.GetString(base64Bytes);
    }
}
